//
//  UITextField+MLKit.m
//  TycoonSale
//
//  Created by molon on 15/7/30.
//  Copyright (c) 2015年 molon. All rights reserved.
//

#import "UITextField+MLKit.h"
#import "MLRuntime.h"
#import <objc/runtime.h>
#import "NSString+MLKit.h"

static char placeholderColorForTextFieldKey;

@implementation UITextField (MLKit)

+ (void)load
{
    Swizzle([self class], @selector(drawPlaceholderInRect:), @selector(MLKit_hook_drawPlaceholderInRect:));
}

- (void)MLKit_hook_drawPlaceholderInRect:(CGRect)rect
{
    UIColor *placeholderColor = self.placeholderColor;
    if (!placeholderColor) {
        placeholderColor = [UIColor colorWithRed:0.830 green:0.828 blue:0.865 alpha:1.000];
    }
    UIFont *font = self.font;
    if (!font) {
        font = [UIFont systemFontOfSize:16.0f];
    }
    
    CGFloat height = [self.placeholder singleHeightWithFont:self.font];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = self.textAlignment;
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    [self.placeholder drawInRect:CGRectMake(0, (rect.size.height-height)/2, rect.size.width, height) withAttributes:@{NSFontAttributeName:font, NSForegroundColorAttributeName:placeholderColor, NSParagraphStyleAttributeName:paragraphStyle}];
}

- (UIColor *)placeholderColor
{
    return objc_getAssociatedObject(self,&placeholderColorForTextFieldKey);
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    static NSString * key = @"placeholderColor";
    
    [self willChangeValueForKey:key];
    objc_setAssociatedObject(self, &placeholderColorForTextFieldKey, placeholderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self didChangeValueForKey:key];
    
    [self setNeedsDisplay];
}
@end
